package com.ccrfid.rmc6.service.business.chongqing.baodeng;

import com.ccrfid.rmc6.service.business.chongqing.baodeng.pojo.*;
import com.ccrfid.rmc6.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class BaodengDataServiceImpl implements BaodengDataService {
    private static final Logger logger = LoggerFactory.getLogger(BaodengDataServiceImpl.class);
    private static final String api_GetSchedule = "/api/CQEK/GetSchedule";
    private static final String colNames = "ScheduleDate,DutyPostName,DutyShiftName,StartTime,EndTime,PoliceId,PoliceName";

    @Value("${chongqing.baodeng.url}")
    private String serviceUrl;
    @Value("${chongqing.baodeng.username}")
    private String username;
    @Value("${chongqing.baodeng.password}")
    private String password;

    @Override
    public List<PatrolScheduleDto> getPatrolSchedule(String date) {
        List<QueryItem> list = new ArrayList<>();
        list.add(new QueryItem("Date", date, "="));
        QueryAnd query = new QueryAnd();
        query.setAnd(list);

        try {
            Client client = ClientBuilder.newClient();
            Response response = client.target(serviceUrl)
                    .path("api")
                    .path(username)
                    .path("GetSchedule")
                    .queryParam("pageIndex", 1)
                    .queryParam("pageSize", 100)
                    .queryParam("colNames", colNames)
                    .queryParam("where", URLEncoder.encode(query.toString(), "UTF-8"))
                    .request(MediaType.APPLICATION_JSON)
                    .header("Authorization", password)
                    .get();
            if (response.getStatus() == 200) {
                String content = response.readEntity(String.class);
                logger.debug("GetSchedule return: {}", content);
                RespData respData = JsonUtil.INSTANCE.readValue(content, RespData.class);
                if (respData.getResCode().equals(1)) {
                    logger.debug("GetSchedule success, return {}", respData.toString());
                    List<PatrolScheduleDto> table = respData.getData().getTable();
                    if (table != null && table.size() > 0) {
                        return table.stream()
                                .filter(item -> item.getScheduleDate().equals(date))
                                .collect(Collectors.toList());
                    } else {
                        return null;
                    }
                } else {
                    logger.error("GetSchedule error, return {}", respData.toString());
                    return null;
                }
            } else {
                logger.error("GetSchedule error, httpStatus: {}", response.getStatus());
                return null;
            }
        } catch (Exception ex) {
            logger.error("ex: {}", ex.getMessage());
            ex.printStackTrace();
            return null;
        }
    }

    @Override
    public void postMsgPatrol(MsgPatrol msgPatrol) {
        try {
            Client client = ClientBuilder.newClient();
            Response response = client.target(serviceUrl)
                    .path("api")
                    .path(username)
                    .path("MsgPatrol")
                    .request(MediaType.APPLICATION_JSON)
                    .header("Authorization", password)
                    .post(Entity.entity(msgPatrol, MediaType.APPLICATION_JSON));
            if (response.getStatus() == 200) {
                String content = response.readEntity(String.class);
                logger.debug("post MsgPatrol return: {}", content);
                RespData respData = JsonUtil.INSTANCE.readValue(content, RespData.class);
                if (respData.getResCode().equals(1)) {
                    logger.debug("post MsgPatrol success.");
                } else {
                    logger.error("post MsgPatrol error.");
                }
            } else {
                logger.error("post MsgPatrol error, httpStatus: {}", response.getStatus());
            }
        } catch (Exception ex) {
            logger.error("ex: {}", ex.getMessage());
            ex.printStackTrace();
        }
    }
}
